package jp.co.apl.haven.ao;

import static jp.dev7.ao.DBParamUtil.*;

import java.sql.SQLException;
import java.util.Date;

import jp.co.apl.haven.ao.entity.AnswerEntity;
import jp.co.apl.haven.ao.exception.DaoException;
import jp.co.apl.haven.generated.HavenProtos.Answer;
import jp.co.apl.haven.generated.HavenProtos.AnswerList;
import jp.co.apl.haven.persistence.Persistence;
import jp.dev7.ao.Tx;
import jp.dev7.ao.Tx.Execution;
import net.java.ao.EntityManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

public class PersistenceImpl implements Persistence {

    private Logger log = LoggerFactory.getLogger(PersistenceImpl.class);

    @Inject
    private EntityManager entityManager;

    public void saveAnswer(Answer answer) {
        log.debug("saveAnswer start (answer = " + answer + ")");

        try {

            // insert
            entityManager.create(
                AnswerEntity.class,
                p("terminalId", answer.getTerminalId()),
                p("questionId", answer.getQuistionId()),
                p("answer", answer.getAnswer()),
                p("answeredDate", new Date(answer.getAnsweredDate())));

            log.debug("saveAnswer end");
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }

    @Override
    public void saveAnswerList(final AnswerList answerList) {
        Tx.execute(entityManager, new Execution<Void>() {
            @Override
            public Void execute() {
                for (Answer answer : answerList.getAnswerList()) {
                    saveAnswer(answer);
                }
                return null;
            }
        });
    }
}
